// 公共接口
import { mAxios, encodeURL } from "./axios.js";

// 表结构
const generalQuerySchema = (module) => {
  return mAxios.post(`/common/${module}/schema`)
}
// 新增
const generalAdd = (module, params) => {
  return mAxios.post(`/common/${module}/add`, params)
}
// 删除
const generalDelete = (module, params) => {
  return mAxios.post(`/common/${module}/delete`, params)
}
// 修改
const generalUpdate = (module, params) => {
  return mAxios.post(`/common/${module}/update`, params)
}
// 查询 (存在默认参数，所以外界可以不传)
const generalQuery = (module, params) => {
  const data = {
    page: 0,
    size: 1000,
    filters: [],
    sorts: ["id"],
    columns: [],
    sorted: "asc",
    ...params
  }
  return mAxios.post(`/common/${module}/list/query`, data)
}
// 查询明细
const generalQueryDetail = (module, params) => {
  return mAxios.get(`/common/${module}/detail`, { params: encodeURL(params) })
}

/**从数据字典中获取下拉框选项
 * @param {*} fieldName 数据字典-字段名
 * @param {*} valueType 值类型（由于数据字典中存储的值类型统一为string，但选项可能要int类型）
 * @returns 
 */
const getOptionsFromLogDict = (fieldName, valueType) => {
  return new Promise((resolve, reject) => {
    const params = {
      fieldName,
    };
    mAxios
      .get("audit/logDict/get", { params: encodeURL(params) })
      .then((res) => {
        resolve(
          res.data.map((item) => {
            switch (valueType) {
              case 'int':
                item.source = parseInt(item.source)
                break;
            }
            return {
              label: item.name,
              value: item.source,
            };
          })
        );
      }).catch(() => {
        reject()
      })
  });
};

export const commonApi = {
  generalQuerySchema,
  generalAdd,
  generalDelete,
  generalUpdate,
  generalQuery,
  generalQueryDetail,
  getOptionsFromLogDict
}